# utils.py
# 工具函数：数据库初始化
from models import Base
from deps import engine

def init_db():
    """初始化数据库表结构并插入初始卡牌数据"""
    Base.metadata.create_all(bind=engine)
    # 插入10个卡牌
    from sqlalchemy.orm import Session
    from models import Card
    session = Session(bind=engine)
    # 检查是否已存在卡牌，避免重复插入
    if session.query(Card).count() == 0:
        cards = [
            Card(code=f"YGO-{i:03d}", name=f"卡牌{i}", rarity="R", type="怪兽", description=f"第{i}张卡牌")
            for i in range(1, 11)
        ]
        session.add_all(cards)
        session.commit()
    # 插入演示用户
    from models import User, UserCard, Order, CartItem
    from passlib.context import CryptContext
    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
    if session.query(User).count() == 0:
        users = [
            User(username=f"user{i}", email=f"user{i}@test.com", hashed_password=pwd_context.hash("password"), nickname=f"用户{i}", is_seller=(i%2==0))
            for i in range(1, 4)
        ]
        session.add_all(users)
        session.commit()
        users = session.query(User).all()
        user_ids = [u.id for u in users]
    else:
        users = session.query(User).all()
        user_ids = [u.id for u in users]
    # 插入用户卡牌
    if session.query(UserCard).count() == 0:
        cards = session.query(Card).all()
        user_cards = []
        for i, user in enumerate(users):
            for card in cards[i*3:(i+1)*3]:
                user_cards.append(UserCard(owner_id=user.id, card_id=card.id, quantity=2+i, price=10.0+i*5))
        session.add_all(user_cards)
        session.commit()
    # 插入订单
    if session.query(Order).count() == 0:
        user_cards = session.query(UserCard).all()
        orders = []
        for i, uc in enumerate(user_cards):
            # 用真实user_ids循环分配买家
            if uc.owner_id in user_ids:
                idx = user_ids.index(uc.owner_id)
                buyer_id = user_ids[(idx + 1) % len(user_ids)]
            else:
                buyer_id = user_ids[0]
            seller_id = uc.owner_id
            orders.append(Order(buyer_id=buyer_id, seller_id=seller_id, user_card_id=uc.id, quantity=1, total_price=uc.price, status="pending"))
        session.add_all(orders)
        session.commit()
    # 插入购物车
    if session.query(CartItem).count() == 0:
        user_cards = session.query(UserCard).all()
        cart_items = []
        for i, uc in enumerate(user_cards):
            cart_items.append(CartItem(user_id=uc.owner_id, user_card_id=uc.id, quantity=1))
        session.add_all(cart_items)
        session.commit()
    session.close() 